// AI聊天组件
import React, { Fragment, useRef, useState } from "react";
import styles from "./styles.module.less";
import { Input } from "antd";
import send from "@/assets/icons/send.png";
import CryptoJS from "crypto-js";

const AIChat: React.FC = () => {
  /*
    消息区域
    */
  const [chatList, setChatList] = useState<any[]>([
    {
      myContent: `你好`,
    },
    {
      AIContent: "你好，我是AI助手，有什么可以帮助你的吗？",
    },
  ]);
  const AiChatListRef = useRef([
    {
      myContent: `你好`,
    },
    {
      AIContent: "你好，我是AI助手，有什么可以帮助你的吗？",
    },
  ]);

  const chatArea = () => {
    return (
      <>
        {chatList.map((message, index) => (
          <Fragment key={`${index}`}>
            {message.AIContent && (
              <div className={`${styles.chatBubble} ${styles.left}`}>
                {message.AIContent}
              </div>
            )}
            {message.myContent && (
              <div className={`${styles.chatBubble} ${styles.right}`}>
                {message.myContent}
              </div>
            )}
          </Fragment>
        ))}
      </>
    );
  };

  /*
  输入区域
  */
  const [inpValue, setInpValue] = useState("你好");
  // 访问讯飞星火 API 的方法
  function initUrl(data: string) {
    // 获取当前时间的 GMT 字符串
    const currentDate = new Date().toUTCString();

    // 定义星火 API 的主机和路径
    const host = "spark-api.xf-yun.com";
    const path = "/v3.5/chat";

    // 构建用于签名的请求头
    const tmp = `host: ${host}\ndate: ${currentDate}\nGET ${path} HTTP/1.1`;

    const APISecret = "ZmNiMjEzNTYzY2ZmMjU5YzhjYjRkMzYy"; // 替换为你的 APISecret

    // 使用 HMAC-SHA256 算法结合 APISecret 对 tmp 进行签名
    const signature = CryptoJS.HmacSHA256(tmp, APISecret);

    // 将签名后的摘要转换为 Base64 编码
    const tmp_sha = CryptoJS.enc.Base64.stringify(signature);

    // 构建 authorization_origin 字符串
    const APIKey = "f8c3afb1bd1267b26c74cb2d695e4eeb"; // 替换为你的 APIKey
    const authorization_origin = `api_key="${APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="${tmp_sha}"`;

    // 使用 btoa() 进行 Base64 编码
    const authorization = btoa(authorization_origin);

    // 构建最终的参数对象
    const params = {
      authorization: authorization,
      date: currentDate,
      host: host,
    };

    // 构建最终的 URL
    const urlParams = new URLSearchParams(params).toString();
    const finalURL = `wss://${host}${path}?${urlParams}`;

    console.log("生成的最终 URL：", finalURL);
    const socket = new WebSocket(finalURL);
    // 当连接打开时发送聊天请求
    socket.addEventListener("open", function () {
      console.log("讯飞星火连接sock连接成功!!!!");
      socket.send(
        JSON.stringify({
          header: {
            app_id: "6c1a2059",
          },
          parameter: {
            chat: {
              domain: "generalv3.5",
              temperature: 0.5,
              max_tokens: 1024,
            },
          },
          payload: {
            message: {
              text: [
                {
                  role: "user",
                  content: data,
                },
              ],
            },
          },
        })
      );
    });

    // 监听 WebSocket 的消息事件
    socket.addEventListener("message", function (event) {
      const res = JSON.parse(event.data).payload.choices.text[0];
      console.log(res);
      const newMessage = AiChatListRef.current.slice();
      newMessage[AiChatListRef.current.length - 1].AIContent += res.content;
      setChatList(newMessage);
    });
    // 监听 WebSocket 的错误事件
    socket.addEventListener("error", function (event) {
      console.error("WebSocket 发生错误：", event);
    });

    // 监听 WebSocket 的关闭事件
    socket.addEventListener("close", function (event) {
      if (event.wasClean) {
        console.log(
          `WebSocket 已关闭，代码=${event.code}，原因=${event.reason}`
        );
      } else {
        console.error("WebSocket 连接断开"); // 例如服务器宕机或网络问题
      }
    });
  }
  const sendMsg = () => {
    console.log("发送消息");
    const obj = {
      myContent: inpValue,
    };
    const obj2 = {
      AIContent: "",
    };
    AiChatListRef.current = [...chatList, obj, obj2];

    setChatList(AiChatListRef.current);

    // setChatList(AiChatListRef.current);

    // startTransition(() => {
    //   initUrl(inpValue);
    // });

    initUrl(inpValue);
    // addChat({ userId: userInfo.id, content: inpValue }).then((res: any) => {
    //   console.log(res);
    //   socketRef.current.emit("publish", {
    //     userId: userInfo.id,
    //     content: inpValue,
    //     name: userInfo.name,
    //     avatar: userInfo.avatar,
    //     time: "2024-07-29 17:16:10",
    //   });
    setInpValue("");
    // });
  };
  const inputArea = () => {
    return (
      <>
        <div className={styles.input}>
          <div className={styles.inputEmoji}></div>
          <Input
            placeholder="Basic usage"
            value={inpValue}
            onChange={(e) => {
              setInpValue(e.target.value);
            }}
            onKeyDown={(e) => {
              if (e.key === "Enter") {
                sendMsg();
              }
            }}
          />
          <div className={styles.inputIcon} onClick={sendMsg}>
            <img className={styles.img} src={send} alt="Send Icon" />
          </div>
        </div>
      </>
    );
  };

  return (
    <div className={styles.AIChat}>
      <div className={styles.chatArea}>{chatArea()}</div>
      <div className={styles.inputArea}>{inputArea()}</div>
    </div>
  );
};
export default AIChat;
